#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Descripttion:
# version: 0.0.1
# Author: Wenwei Fu (2516800961@qq.com)
# FilePath: /fastapi_byd/app/api/routes/expert.py
# Create: 2021-01-04 16:37:40
# LastAuthor: Wenwei Fu
# lastTime: 2021-01-10 15:01:42
# --------------------------------------------------------

import os
import time
import uuid
import datetime
from typing import Optional
from pydantic import BaseModel
from app.core.config import ImagesUrl, ROOT_FILE_PATH
from fastapi import APIRouter, Request, Body, Depends, HTTPException
from fastapi import File, UploadFile
from fastapi.responses import StreamingResponse, FileResponse
from app.api.dependencies.authentication import get_current_user_authorizer
from app.db.database import get_db

router = APIRouter()

# 文件大小格式化
def sizeFormat(size, is_disk=False, precision=2):
    '''
    size format for human.
        byte      ---- (B)
        kilobyte  ---- (KB)
        megabyte  ---- (MB)
        gigabyte  ---- (GB)
        terabyte  ---- (TB)
        petabyte  ---- (PB)
        exabyte   ---- (EB)
        zettabyte ---- (ZB)
        yottabyte ---- (YB)
    '''
    formats = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    unit = 1000.0 if is_disk else 1024.0
    if not(isinstance(size, float) or isinstance(size, int)):
        raise TypeError('a float number or an integer number is required!')
    if size < 0:
        raise ValueError('number must be non-negative')
    for i in formats:
        size /= unit
        if size < unit:
            return f'{round(size, precision)}{i}'
    return f'{round(size, precision)}{i}'

# 文件上传功能
@router.post("/file_upload", name="上传文件", dependencies=[Depends(get_db), Depends(get_current_user_authorizer())])
async def file_upload(
    file: UploadFile = File(...),
    request: Request=None
):
    start = time.time()
    try:
        FilePath = os.path.join(ROOT_FILE_PATH, file.filename)
        print('保存路径为：', FilePath)
        # is_exists = os.path.exists(FilePath)
        # print('是否存在：', is_exists)
        # if is_exists == True:
        #     return {
        #         "code": 202,
        #         "message": "已存在同名文件",
        #         "data": {
        #             "filename": file.filename
        #         }
        #     }
        # 读文件，并保存起来
        res = await file.read()
        with open(FilePath, "wb") as f:
            f.write(res)
            print('保存成功。')
        # with open(FilePath, 'rb') as fp:
        #     f = fp.read()
        #     file_md5 = hashlib.md5(f).hexdigest()
        #     print('文件的md5值：', file_md5)

            return {
                "code": 200,
                "message": "上传成功",
                "data": ImagesUrl + '/traffic_files/previewfile/' + file.filename
            }
    except Exception as e:
        return {
            "code": 201,
            "message": str(e),
            "data": {
                'upload_time': time.time() - start,
                'filename': file.filename
            }
        }

@router.get("/previewfile/{file_name}", name="获取文件下载链接", dependencies=[Depends(get_db)])
async def preview_file(
    file_name: str
):
    file_name = os.path.join(ROOT_FILE_PATH, file_name)
    print(file_name)
    return FileResponse(file_name)
    # file_like = open(file_name, mode="rb")
    # return FileResponse(file_like)


